<?php

namespace app\finance\controller;

use app\devices\service\DevicesService;
use app\devices\service\OrderService;
use think\admin\Controller;
use think\cache\driver\Redis;
use think\facade\Db;

/**
 * 财务管理
 * Class Index
 * @package app\finance\controller
 */
class Index extends Controller
{
    private $table = 'JcgDevicesOrder';

    /**
     * 柜点收益
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function store(){
        $this->index('柜点收益');
    }

    /**
     * 柜子收益
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function device(){
        $this->index('柜子收益');
    }

    /**
     * 公司收益
     * @auth true
     * @menu true
     * @param string $title
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index($title='公司收益')
    {
        $this->title = $title;

        $this->fee_types = [3=>'按时', 2=>'按次', 1=>'免费'];

        $now_date = input("create_at", date("Y-m-d", strtotime('-7 day')).' - '.date("Y-m-d"));
        $this->assign("create_at", $now_date);

        $type = input('type/d', 3);
        $this->assign("type", $type);

        $times = explode(" - ", $now_date);

        switch ($type){
            case "1":
                //年
                if($times && $times[0]!=""){
                    $time = $times[0].'-01-01';
                    $start_time = strtotime($time);
                    $end_time = strtotime($times[0].'-12-31 23:59:59');
                }
                $format = 'YEAR(create_at)';
                break;
            case "2":
                //月
                if($times && $times[0]!=""){
                    $time = $times[0].'-01';
                    $start_time = strtotime($times[0].'-01');
                    $end_time = strtotime($times[0].'-'.date('t',strtotime($time)).' 23:59:59');
                }
                $format = 'MONTH(create_at)';
                break;
            case "3":
            default:
                //日
                if($now_date==""){
                    $now_date = date("Y-m-d", strtotime('-7 day')).' - '.date("Y-m-d");
                    $this->assign("create_at", $now_date);
                    $times = explode(" - ", $now_date);
                }
                $start_time = strtotime($times[0]);
                $end_time = strtotime($times[1].' 23:59:59');
                $format = 'DATE(create_at)';
                break;
        }

        $where = [
            ['status', '=', 2],
            ['store_id', '<>', 15]
        ];

        if(isset($start_time) && isset($end_time)){
            $where[] = ['create_time', 'between', [$start_time, $end_time]];
        }

        $group = "time";
        $order = "time DESC";

        $user = $this->app->session->get("user");
        $map = $stores = [];
        if($user['id']!=10000){
            $authorize = str2arr($user['authorize'] ?? '');
            if(in_array(1, $authorize)){
                $stores = str2arr($user['stores'] ?? '');
                if($stores) {
                    $map[] = ['id', "in", $stores];
                    $where[] = ['store_id', "in", $stores];
                }
            }

            if(in_array(3, $authorize)){
                $stores = $this->app->db->name("jcg_store")->where("sales_id", $user['id'])->column("id");
                $map[] = ['id', "in", $stores];
                $where[] = ['store_id', "in", $stores];
            }
        }
        $this->user_stores = $stores;

        $is_store = input("is_store", 0);

        $this->stores = $this->app->db->name("jcg_store")->where($map)->column("name,share_ratio,sales_id", "id");

        $sales = [];
        if($is_store){
            $group = "store_id, time";
            $order = "time DESC,store_id ASC";
        }
        $this->assign("is_store", $is_store);

        $store_id = input("store_id/d",0);
        if($store_id){
            $where[] = ['store_id', '=', $store_id];
        }

        $this->assign("store_id", $store_id);

        $is_device = input("is_device", 0);
        if($is_device){
            $this->assign("devices", $this->app->db->name("jcg_devices")->where('store_id', "in", array_keys($this->stores))->column("device_name", "id"));
            $group = "d_id, time";
            $order = "time DESC, d_id ASC";
        }
        $this->assign("is_device", $is_device);

        if($is_device || $is_store){
            $sale_ids = array_column($this->stores, 'sales_id','id');
            if($sale_ids) {
                $this->salesmans = $sales = $this->app->db->name("system_user")->where("id", "in", $sale_ids)->column("nickname",'id');
            }
            $this->sale_id = input("sale_id/d",0);
            if($this->sale_id){
                $store_ids = [];
                foreach ($sale_ids as $key=>$val){
                    if($val==$this->sale_id) $store_ids[] = $key;
                }
                if($store_ids) $where[] = ['store_id', "in", $store_ids];
            }
        }

        $device_id = input("device_id/d",0);
        if($device_id){
            $where[] = ['d_id', '=', $device_id];
        }
        $this->assign("device_id", $device_id);

        $fields = 'id, fee_type, ' . $format . ' AS time, GROUP_CONCAT(CONCAT_WS(\'_\',fee_type,amount_total,money,share_ratio,DAY(create_at))) as info, extends, create_time, COUNT(IF(status>0,id,NULL)) as o_num, d_id, store_id';

        $limits = $this->app->db->name($this->table)->where($where)->group($group)->column('DATE_FORMAT(FROM_UNIXTIME(create_time), '.$format.') as time');
        $total = count($limits);

        $limit = $this->app->request->get('limit', $this->app->cookie->get('limit'));
        $page = $this->app->request->get('page', 1);

        if (input('output') === 'json') {
            $limit = $total;
        }

        $subSql = $this->app->db->name($this->table)->where($where)->field("id, ".$format." as time, `status`, d_id, store_id, IF(fee_type=3,amount_total*share_ratio,money*share_ratio) as amount, IF(fee_type=3,amount_total,money) as amount_a, extends, create_time")->buildSql();

        $list = Db::query("SELECT id, d_id, store_id, create_time, COUNT(IF(amount_a>0,id,NULL)) as o_num, sum(amount_a) as total, sum(amount)/100 as share_total, time, extends FROM {$subSql} a GROUP BY ".$group." ORDER BY ".$order." limit ".($page-1)*$limit.",".$limit);

//        $list = $this->app->db->name($this->table)->where($where)->field($fields)->group($group)->limit(($page-1)*$limit, $limit)->order($order)->select()->toArray();
        $boxs = [];
        if($list){
            if($is_device){
                $d_ids = array_column($list, 'd_id');
                $boxs = $this->app->db->name('jcg_boxs')->group("d_id")->where("user_type",0)->where("d_id", "in", $d_ids)->column("count(id)",'d_id');

                $devices = $this->app->db->name("jcg_devices")->where("id", "in", $d_ids)->column("id, store_id, device_name",'id');
            }else if($is_store){
                $s_ids = array_column($list, 'store_id');
                $devices = $this->app->db->name("jcg_devices")->where("store_id", "in", $s_ids)->column("id, store_id, device_name",'id');
                $d_ids = $s_d_ids = [];
                foreach ($devices as $row){
                    $d_ids[] = $row['id'];
                    $s_d_ids[$row['store_id']][] = $row['id'];
                }
                $boxs = $this->app->db->name("jcg_boxs")->where("user_type",0)->where('d_id', "in", $d_ids)->group("d_id")->column("count(id)", "d_id");
            }
        }

        $all_total = 0;
        foreach ($list as &$row){
            $box_num = 0;
            if(isset($boxs) && $is_device){
                $box_num = $boxs[$row['d_id']]??0;
            }else if(isset($boxs) && $is_store){
                foreach ($boxs as $key=>$val){
                    if(isset($s_d_ids[$row['store_id']]) && $s_d_ids[$row['store_id']] && in_array($key, $s_d_ids[$row['store_id']])){
                        $box_num += $val;
                    }
                }
            }
            if($type==2){
                $row['time'] = date("Y-",$row['create_time']). ($row['time']<10?'0'.$row['time']:$row['time']);
            }

            $row['kxl'] = $box_num?($type==2?sprintf("%.2f",$row['o_num'] / $box_num / 20  * 100):sprintf("%.2f",$row['o_num'] / $box_num * 100)):0;
            $row['box_num'] = $box_num;

            $all_total += $row['total'];

            if($is_store || $is_device){
                $row['share_total'] = sprintf("%.2f",$row['share_total']);

                $row['store_sales'] = $sales[$this->stores[$row['store_id']]['sales_id']??0]??'/';
            }else{
                $row['share_total'] = $row['total'] - sprintf("%.2f",$row['share_total']);
            }

            $extends = json_decode($row['extends'], true);
            $device_name = explode(" ", $extends['device_name']);
            $device_name_a = explode(" ", $devices[$row['d_id']]['device_name']??'');
            $row['store_name'] = $device_name[0]!=$device_name_a[0]?$device_name_a[0]."( ".$device_name[0]." )":$device_name_a[0];
            $row['device_name'] = $device_name[1];
        }

        $this->assign("all_total", $all_total);

        if (input('output') === 'json') {
            $this->success('获取数据成功', ['list'=>$list, 'page'=>["current"=>$page, "limit"=>$limit, "pages", "total"=>$total]]);
        }

        $this->assign("list", $list);

        $this->_page($this->table, 1, 0, $total);

        $this->fetch('index');
    }

    /**
     * 列表数据处理
     * @param $data
     */
    public function _index_page_filter(&$data){
        if($data){

        }
    }
}